package cc.lucien.Controller;

import cc.lucien.entity.User;
import cc.lucien.entity.UserList;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @author lucien-ma
 * @date 2021/9/5
 * @apiNote
 */
@Controller
@RequestMapping(value = "/hello")
public class HelloHandler {

    @RequestMapping("/index")
    public String index(@RequestParam("num") Integer id, @RequestParam("str") String name) {
        System.out.println("接收到了请求,参数是：id=" + id + ", name=" + name);
        return "index";
    }

    /**
     * RESTful 风格
     *
     * @param id
     * @param name
     * @return
     */
    @RequestMapping(value = "/restful/{id}/{name}", method = RequestMethod.GET)
    public String restful(@PathVariable Integer id, @PathVariable String name) {
        System.out.println(id + "-" + name);
        return "redirect:/index.jsp";
    }

    @RequestMapping("/cookie")
    public String getCookie(@CookieValue("JSESSIONID") String sessionId) {
        System.out.println(sessionId);
        return "index";
    }

    /**
     * 参数绑定 pojo 类型
     * @param user
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String addUser(User user) {
        System.out.println(user);
        return user.toString();
        //return "index";
    }

    @RequestMapping("/baseType")
    // 加了这个注解就不走视图解析器，直接把字符串返回到前端页面
    @ResponseBody
    public String baseType(int id) {
        return "id:"+id;
    }

    @RequestMapping("/packageType")
    @ResponseBody
    public String packageType(
            @RequestParam(value = "id",     // 参数绑定
                    required = true,        // id 参数必传
                    defaultValue = "0") Integer id) {  // 不传默认值为 0
        return "id:"+id;
    }

    /**
     * 数组类型的数据绑定
     * @param names
     * @return
     */
    @RequestMapping("/arrayType")
    @ResponseBody
    public String arrayType(String[] names) {
        StringBuffer stringBuffer = new StringBuffer();
        for (String name : names) {
            stringBuffer.append(name).append(" ");
        }
        return stringBuffer.toString();
    }

    /**
     * list 数据绑定，参数不能直接写 List
     * 需要定义一个包含 List 的 POJO
     * @param userList
     * @return
     */
    @RequestMapping("/listType")
    @ResponseBody
    public String listType(UserList userList) {
        StringBuffer stringBuffer = new StringBuffer();
        for (User user : userList.getUsers()) {
            stringBuffer.append(user).append(" ");
        }
        return "用户: " + stringBuffer.toString();
    }

    /**
     * json 数据类型的 数据绑定
     * @param user
     * @return
     */
    @RequestMapping("/jsonType")
    @ResponseBody
    public User jsonType(@RequestBody User user) {
        System.out.println(user);
        user.setId(2);
        return user;
    }
}
